import { DataService } from '@services/data.service';
import { Component, OnInit, ElementRef, Renderer2 } from '@angular/core';
import {
  ModalController,
  NavController,
  IonNav,
  PopoverController
  // NavParams,
} from '@ionic/angular';

import { QRScannerModal } from '@modals/qr-scanner/qr-scanner';
import { HttpService } from '@services/http.service';
// import { SystemPage } from '../system/system';
import { CacheService } from '@services/cache.service';
// import { RoomLiftPage } from '../../home/room-lift/lift';
// import { RoomFirePage } from '../room-fire/fire';

import { MultipleSelectModal } from '@modals/multiple-select/multiple-select';
import { PicUploadService } from '@services/picUpload.service';
import { Router, ActivatedRoute } from '@angular/router';
// import { AlarmReportPage } from '../alarm-report/alarm-report';
import { PopoverPage } from '@pages/home/popover/popover';
@Component({
  selector: 'index-project',
  templateUrl: 'page.html',
  styleUrls: ['style.scss'],
})
export class IndexProjectPage implements OnInit {

  params;
  companyId;
  companyName;
  projectId;
  projectName;
  userId;
  canGoBack = true;
  PList;
  TargetList = []; // 项目层指标
  systemList = [];
  myProjects = [];
  informOption = {
    step: 1,
    timer: 50,
    left: 25,
    right: 10,
  };
  person = {
    headStyle: {},
    headStylebg: {}
  };
  TargetInterval; // 指标定时器
  indexDataList = [
    { 'IndexCode': '105102', 'IndexName': '告警总数', 'Data1': 0, 'Data2': 0, Unit1: '次', isShow: false },
    { 'IndexCode': '105103', 'IndexName': '告警及时响应率', 'Data1': 0, 'Data2': 0, Unit1: '%', isShow: false },
    { 'IndexCode': '105104', 'IndexName': '告警及时恢复率', 'Data1': 0, 'Data2': 0, Unit1: '%', isShow: false },
    { 'IndexCode': '103294', 'IndexName': '总能耗环比', 'Data1': 0, 'Data2': 0, Unit1: '%', isShow: false },
    { 'IndexCode': '105120', 'IndexName': 'IOT在线率', 'Data1': 0, 'Data2': 0, Unit1: '%', isShow: false },
    { 'IndexCode': '103016', 'IndexName': '数据栈', 'Data1': 0, 'Data2': 0, isShow: false },
    { 'IndexCode': '103115', 'IndexName': '传感器', 'Data1': 0, 'Data2': 0, isShow: false },
    { 'IndexCode': '105137', 'IndexName': '物联工单完成', 'Data1': 0, 'Data2': 0, Unit1: '%', isShow: false }
  ];

  breakList = [
    '通知1：拉拉阿拉啦啦啊啊啊啊啊啊',
    '通知2：拉拉阿拉啦啦啊啊啊啊啊啊',
    '通知3：拉拉阿拉啦啦啊啊啊啊啊啊',
  ];

  blocInfo = {
    BlocName: '',
    Comprehensive: { Title: '', Evaluation: '', Percent: null },
    BlocBGP: '',
    BlocUrl: '',
    Announcement: '关于开展预交物业费送礼品活动通知',
  };

  flowList = [
    //   { Title: 'xxx1', CreateTime: '今天 12:00', IsOwner: true },
    //   { Title: 'xxx2', CreateTime: '今天 9:00', IsOwner: true },
    //   { Title: 'xxx3', CreateTime: '昨天 13:30', IsOwner: false },
  ];


  constructor(
    private modalCtrl: ModalController,
    private httpService: HttpService,
    private el: ElementRef,
    private renderer: Renderer2,
    // private navParams: NavParams,
    private navCtrl: NavController,
    private dataservice: DataService,
    private cache: CacheService,
    private picUploadService: PicUploadService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private popoverCtrl: PopoverController
  ) {
    this.userId = this.cache.userinfo.userId;
    this.PList = this.cache.functionPoint[this.cache.functionPoint.length - 1].children;
    this.activatedRoute.queryParams.subscribe(params => {
      this.params = params;
      this.companyId = params.companyId ? params.companyId : this.cache.currentCompany.companyId;
      this.companyName = params.companyName ? params.companyName : this.cache.currentCompany.companyId;
      if (this.cache.functionPoint.length === 1) {
        this.canGoBack = false;
      }
      this.projectId = params.projectId || this.cache.currentProject.projectId;
      this.projectName = params.projectName || this.cache.currentProject.projectName;
    });
  }

  ngOnInit() {
  }

  ionViewWillEnter() {
    const elements = document.querySelectorAll('ion-tab-bar');
    if (elements != null) {
      Object.keys(elements).map((key) => {
        elements[key].style.display = 'flex';
      });
    }
    this.setHeadAndBack();
    this.init();
  }

  ionViewWillLeave() {
    const elements = document.querySelectorAll('ion-tab-bar');
    if (elements != null) {
      Object.keys(elements).map((key) => {
        elements[key].style.display = 'none';
      });
    }
    if (this.TargetInterval) {
      clearInterval(this.TargetInterval);
    }
  }

  setHeadAndBack() {
    this.person.headStylebg = { 'background': 'linear-gradient(#54BFF4, #1FB5FF)' };
    this.person.headStyle = { 'background-image': 'url(assets/imgs/default.png)' };
    this.picUploadService.getAvatar().subscribe(imgdata => {
      if (imgdata.isDefault) {
        this.person.headStylebg = { 'background': 'linear-gradient(#54BFF4, #1FB5FF)' };
      } else {
        this.person.headStylebg = { 'background-image': 'url(' + imgdata.url + ')' };
      }
      this.person.headStyle = { 'background-image': 'url(' + imgdata.url + ')' };
    });
  }

  // 初始化页面数据
  init() {
    const Plist = [];
    const Tlist = [];
    for (let i = 0; i < this.PList.length; i++) {
      if (this.PList[i].menuType === 10) {
        // 平台层指标
        Tlist.push(this.PList[i]);
      } else {
        Plist.push(this.PList[i]);
      }
    }
    this.PList = Plist;
    this.TargetList = Tlist;
    for (let i = 0; i < this.indexDataList.length; i++) {
      for (let j = 0; j < this.TargetList.length; j++) {
        if (this.TargetList[j].menuName === this.indexDataList[i].IndexName) {
          this.indexDataList[i].isShow = true;
        }
      }
    }
    this.getUserSystemList();
    this.getProjects();
    this.getTarget();
  }

  getUserSystemList() {
    this.dataservice.getSystemList(this.projectId).subscribe(res => {
      if (res.success) {
        this.systemList = res.data.datas.sort(this.compare('sort'));
      }
    });
  }

  // 对系统进行排序
  compare(property) {
    return function (a, b) {
      const value1 = a[property];
      const value2 = b[property];
      return value1 - value2;
    }
  }

  // 获取该用户的项目
  getProjects() {
    this.cache.projects.subscribe(data => {
      this.myProjects = data;
    });
  }

  scrollHandler(event) {
    const columnTop = event.scrollTop;
    const opacity = columnTop / 186 >= 1 ? 1 : columnTop / 186;
    const topEle = this.el.nativeElement.querySelector('.project-title');
    this.renderer.setStyle(
      topEle,
      'background',
      'rgba(31,181,255,' + opacity + ')'
    );
  }

  scan() {
    this.modalCtrl.create({ component: QRScannerModal }).then(videoModal => {
      videoModal.present();
    });
  }

  goPage(data) {
    if (data.url.length > 1) {
      this.navCtrl.navigateForward(['tabs/home/' + data.url], {
        queryParams: {
          page: 2
        }
      });
      // this.navCtrl.navigateForward(['tabs/home/keyInspection'], {

      // });
    } else {
      console.log(data.menuName + ',该功能点url不正确或未配置');
      this.navCtrl.navigateForward(['tabs/home/alarmReport'], {
        queryParams: {
          page: 2
        }
      });
    }
  }

  goDeiveSystem(data) {
    const path = 'tabs/home/SystemPage';
    if (data.deviceSysId === 5) {
      this.navCtrl.navigateForward(['tabs/home/RoomLiftPage'], {
        queryParams: {
          projectId: this.projectId,
          projectName: this.projectName,
          systemId: data.deviceSysId,
          systemName: data.deviceSysName,
        }
      });
      // path = 'roomLiftPage';
    } else if (data.deviceSysId === 4) {
      this.navCtrl.navigateForward(['tabs/home/RoomFirePage'], {
        queryParams: {
          projectId: this.projectId,
          projectName: this.projectName,
          systemId: data.deviceSysId,
          systemName: data.deviceSysName,
        },
      });
    } else if (data.deviceSysId === 10) {
      this.navCtrl.navigateForward(['tabs/home/ParkPage'], {
        queryParams: {
          // projectId: this.projectId,
          // projectName: this.projectName,
          // systemId: data.deviceSysId,
          // systemName: data.deviceSysName,
        },
      });
    } else {
      data.projectId = this.projectId;
      data.projectName = this.projectName;
      this.navCtrl.navigateForward([path], {
        queryParams: data
      });
    }
  }

  getTarget() {
    this.dataservice.getTarget(105102, 3, this.projectId).subscribe(res => {
      // console.log('获取告警总数指标');
      if (res.data) {
        this.indexDataList[0].Data1 = res.data.alarmNum;
      }
    });
    this.dataservice.getTarget(105103, 3, this.projectId).subscribe(res => {
      // console.log('获取告警及时响应率指标');

      if (res.data) {
        this.indexDataList[1].Data1 = Math.round(res.data.rate);
      }
    });
    this.dataservice.getTarget(105104, 3, this.projectId).subscribe(res => {
      // console.log('获取告警及时恢复率指标');

      if (res.data) {
        this.indexDataList[2].Data1 = Math.round(res.data.rate);
      }
    });
    this.dataservice.getTarget(103294, 3, this.projectId).subscribe(res => {
      // console.log('获取总能耗环比指标');

      if (res.data) {
        if (res.data.yesterdayEnergy) {
          console.log((res.data.todayEnergy - res.data.yesterdayEnergy) / res.data.yesterdayEnergy)
          this.indexDataList[3].Data1 = Math.round(((res.data.todayEnergy - res.data.yesterdayEnergy) / res.data.yesterdayEnergy) * 100);
        } else {
          this.indexDataList[3].Data1 = null;
        }
      }
    });
    this.dataservice.getTarget(105120, 3, this.projectId).subscribe(res => {
      // console.log('获取IOT在线数指标');
      if (res.data && res.data.totalNum) {
        // this.indexDataList[4].Data1 = res.data.onlineNum;
        // this.indexDataList[5].Data2 = res.data.totalNum;
        console.log(res.data.onlineNum / res.data.totalNum)
        this.indexDataList[4].Data1 = parseFloat(((res.data.onlineNum / res.data.totalNum) * 100).toFixed(1));
      }
    });
    this.dataservice.getTarget(103016, 3, this.projectId).subscribe(res => {
      // console.log('获取数据栈指标');

      if (res.data) {
        this.indexDataList[5].Data1 = res.data.totalNum - res.data.onlineNum;
        this.indexDataList[5].Data2 = res.data.totalNum;
      }
    });
    this.dataservice.getTarget(103115, 3, this.projectId).subscribe(res => {
      // console.log('获取传感器指标');

      if (res.data) {
        this.indexDataList[6].Data1 = res.data.totalNum - res.data.onlineNum;
        this.indexDataList[6].Data2 = res.data.totalNum;
      }
    });
    this.dataservice.getTarget(105137, 3, this.projectId).subscribe(res => {
      // console.log('获取物联工单完成指标');

      if (res.data && res.data.totalNum) {
        this.indexDataList[7].Data1 = Math.round((res.data.recoveryNum / res.data.totalNum) * 100);
      }
    });
  }

  async Search(i) {
    const params = {
      companyId: this.companyId,
      companyName: this.companyName
    };
    const popover = await this.popoverCtrl.create({
      component: PopoverPage,
      componentProps: {
        type: i,
        Page: 2
      },
      backdropDismiss: false,
      cssClass: 'home-popover'
    });
    popover.present();
    const res = await popover.onDidDismiss();
    if (res.data) {
      const data = res.data;
      if (data && data.item) {
        switch (data.type) {
          case '1':
            this.cache.currentProject = data.item;
            this.companyId = data.item.companyId;
            this.companyName = data.item.companyName;
            params.companyId = this.companyId;
            params.companyName = this.companyName;
            this.navCtrl.navigateForward(['tabs/home/indexGroup'],
              {
                queryParams: {
                  type: data.type,
                  companyId: data.item.companyId,
                  companyName: data.item.companyName
                }
              });
            // this.modalCtrl.dismiss();
            break;
          case '2':
            this.cache.currentProject = data.item;
            this.projectId = data.item.projectId;
            this.projectName = data.item.projectName;
            this.init();
            // this.navCtrl.navigateForward(['tabs/home/indexProject'],
            //   {
            //     queryParams: {
            //       type: data.type,
            //       projectId: data.item.projectId,
            //       projectName: data.item.projectName,
            //     }
            //   });
            // this.modalCtrl.dismiss();
            break;
          case '3':
            this.goPage(data.item);
            break;
          case '4':
            this.goDeiveSystem(data.item);
            break;
        }
      }
    }
  }

  navPop() {
    this.navCtrl.pop();
  }
}
